﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using DAL;
using Models;



namespace SMProject
{
    public partial class FrmLogin : Form
    {
        //创建数据访问对象
        private SalesPersonService objService = new SalesPersonService();


        public FrmLogin()
        {
            InitializeComponent();
            //string connString = "Server=localhost;Database=SaleManagerDB;uid=sa;pwd=123456;Trusted_Connection=false;TrustServerCertificate=true";
            //connString = StringSecurity.DESEncrypt(connString);
            //this.test.Text = connString;
        }
        //登录按钮
        private void btnLogin_Click(object sender, EventArgs e)
        {
          //1. 数据验证
          if(this.txtLoginId.Text.Trim().Length == 0 || this.txtLoignPwd.Text.Trim().Length == 0)
            {
                MessageBox.Show("账号和密码必须全部填写！", "登录提示");
                return;
            }

            //2. 将用户账号和密码封装到用户对象
            SalesPerson objPerson = new SalesPerson()
            {
                SalePersonId = Convert.ToInt32(txtLoginId.Text.Trim()),
                LoginPwd = txtLoignPwd.Text.Trim()
            };

            //3. 将用户对象提交数据访问方法实现登录
            try
            {
                objPerson = objService.UserLogin(objPerson);
                if(objPerson == null)
                {
                    MessageBox.Show("账号或密码错误！", "登录提示");
                }
                else
                {
                    //(1)保存用户信息到全局变量
                    Program.currentPerson = objPerson;

                    //(2)将用户登录信息写入日志
                    Program.currentPerson.LoginLogId = objService.WriteLoginLog(new LoginLog()
                    {
                        LoginId = Convert.ToInt32(this.txtLoginId.Text.Trim()),
                        SPName = objPerson.SPName,
                        ServerName = Dns.GetHostName()
                    });


                    //(3)设置登录窗体返回值
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("用户登录出现异常： " + ex.Message);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
